package com.example.nfc1;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.util.Preconditions;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    private NfcAdapter mNfcAdapter = null;
    private PendingIntent mPendingIntent = null;
    private IntentFilter[] mIntentFilter = null;
    private  String[][] mTechList = null;

//    private Context mContext;

    private TextView mTextView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView =findViewById(R.id.tv);
//        mContext = this;
        mTextView.setText("Scan a tag");
        NfcCheck();


        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
//        IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
//        if(intentFilter!=null){
//            Log.d("TAGNFC","not nll");
//        }else{
//            Log.d("TAGNFC"," nll");
//        }
//
//        try {
//            intentFilter.addDataType("*/*");
//        } catch (IntentFilter.MalformedMimeTypeException e) {
//            e.printStackTrace();
//        }
//
//        mIntentFilter =new  IntentFilter[] {intentFilter};
//        mTechList = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null) {
//            resolveIntent(getIntent());
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilter, mTechList);
            resolveIntent(getIntent());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
////        mTextView.setText("scan a tag: "+intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
//        resolveIntent(intent);
//
//    }

    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        Log.d("TAGNFC", "进入 action" + intent.getAction());
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Log.d("TAGNFC", "进入 resolve");
            NdefMessage[] messages = null;
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

            if (rawMsgs != null) {
                messages = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    messages[i] = (NdefMessage) rawMsgs[i];
                    Log.d("TAGNFC", "resolveIntent index:" + (NdefMessage) rawMsgs[i]);
                }
            } else {
                byte[] empty = new byte[]{};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
                messages = new NdefMessage[]{msg};
            }
            // 处理NDEF消息
            processNDEFMsg(messages);
        } else if (Intent.ACTION_MAIN.equals(action)) {
            // 处理应用启动时的动作
            if (intent.getData() != null) {
                // 获取URI数据并进行处理
                String uriString = intent.getDataString();
                Log.d("TAGNFC", "URI: " + uriString);
                // 进行你的处理逻辑
            }
        }
    }

    private  void NfcCheck(){
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            // 设备不支持NFC
            Toast.makeText(this, "设备不支持NFC", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if (!mNfcAdapter.isEnabled()) {
                // NFC未启用，打开系统设置页面
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                startActivity(setNfc);
                return;
            }else{
                Log.d("TAGNFC", "成功启用nfc");
            }
        }
    }
    private void processNDEFMsg(NdefMessage[] messages) {
        Log.d("TAGNFC", "messages " + messages);
        if (messages == null || messages.length == 0) {
            return;
        }

        NdefRecord[] records = messages[0].getRecords();
        if (records.length > 0) {
            parseRTDUriRecord(records[0]);
        }
    }

//    private  void  processNDEFMsg(NdefMessage[] messages){
//        Log.d("TAGNFC", "messages " + messages);
//        if(messages ==null || messages.length ==0){
//            return;
//        }
//        for (int i=0; i<messages.length; i++){
//            int length  = messages[i].getRecords().length;
//            NdefRecord[] records = messages[i].getRecords();
//            for (int j=0; j<length;j++){
//                for (NdefRecord record:records){
////                    parseTextRecord(record);
//                        parseRTDUriRecord(record);
//                }
//
//            }
//        }
//    }

//    @SuppressLint("RestrictedApi")
    private void parseRTDUriRecord(NdefRecord record){
//        Preconditions.checkArgument(Arrays.equals(record.getType(),NdefRecord.RTD_URI));
        byte[] payload  = record.getPayload();
        String prefix = "https://www.test.com";
        byte[] payloadWithoutPrefix = Arrays.copyOfRange(payload, 1, payload.length);
        String fullUrl = prefix + new String(payloadWithoutPrefix, StandardCharsets.UTF_8);
        Log.d("TAGNFC", "结果" + fullUrl);
        mTextView.setText(fullUrl);
    }

//    @SuppressLint("RestrictedApi")
    private void parseTextRecord(NdefRecord record) {
//        Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_TEXT));
        byte[] payload = record.getPayload();
        Byte statusByte = record.getPayload()[0];
        String textEncoding = ((statusByte & 0x80) == 0) ? "UTF-8" : "UTF-16";
        int langLength = statusByte & 0x3F;
//        String langCode = new String(payload, 1, langLength, Charset.forName("UTF-8"));
        try {
            Log.d("TAGNFC", "结果1" + payload.length);
            Log.d("TAGNFC", "结果2" + langLength);
            Log.d("TAGNFC", "结果3" + textEncoding);
//            String payloadText = new String(payload, langLength + 1, payload.length - langLength - 1, textEncoding);
//            Log.d("TAGNFC", "结果" + payloadText);
//            mTextView.setText(payloadText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
